<template>
  <div class="commodity-details">
<!--    <div class="demo-nav">-->
<!--      <div class="demo-nav__title">商品详情</div>-->
<!--      <svg viewBox="0 0 1000 1000" class="demo-nav__back" @click="toBack">-->
<!--        <path fill-rule="evenodd" fill="#969799" d="M296.114 508.035c-3.22-13.597.473-28.499 11.079-39.105l333.912-333.912c16.271-16.272 42.653-16.272 58.925 0s16.272 42.654 0 58.926L395.504 498.47l304.574 304.574c16.272 16.272 16.272 42.654 0 58.926s-42.654 16.272-58.926 0L307.241 528.058a41.472 41.472 0 0 1-11.127-20.023z"></path>-->
<!--      </svg>-->
<!--      <van-icon @click="share('weixin')" class="demo-nav__right" name="share-o" size="20" color="#000000"/>-->
<!--    </div>-->

    <van-nav-bar
      title="商品详情"
      left-text=""
      right-text="分享"
      left-arrow
      @click-left="toBack"
      @click-right="share('weixin')"
    />

    <van-swipe :autoplay="3000">
      <van-swipe-item v-for="(image, index) in images" :key="index">
        <img width="375" height="375" v-lazy="image.picUrl" />
      </van-swipe-item>
    </van-swipe>

    <div class="commodity-details-a">
      <van-row>
        <van-col span="18" style="text-align: left">
          <p style="font-weight: bolder;margin-bottom: 0.5rem">{{product.categoryName}}|{{product.productName}}</p>
          <p style="display: inline-block">￥<span style="font-size: 1.5rem;font-weight: bolder">{{product.price}}</span></p>
          <p style="display: inline-block;font-size: 0.5rem;margin-left: 0.5rem">销量:<span>{{this.xiaoshoushu}}</span></p>
        </van-col>
        <van-col span="6" style="text-align: right">
<!--          <van-icon name="share-o" size="22"/>-->
<!--          <p>分享</p>-->
        </van-col>
      </van-row>
    </div>
    <div class="commodity-details-b">
      <van-row>
        <van-col span="18" style="text-align: left">
          <van-tag plain type="primary" color="red">店铺优惠券</van-tag>
        </van-col>
        <van-col span="6" style="text-align: right;padding-right: 0.5rem;position: relative" @click="showCoupon = true">
          <p style="color:red;font-size: 0.9rem;display: inline-block">领券<van-icon name="arrow" size="13" color="red"/></p>
        </van-col>
      </van-row>
    </div>
    <van-divider/>
    <div class="commodity-details-c">
      <van-row>
        <van-col span="3">
          <van-image round width="2.2rem" height="2.2rem" fit="cover" :src="product.supplierPic"/>
        </van-col>
        <van-col span="13" style="text-align: left">
          <p>{{product.shopsName}}</p>
          <p style="display: inline-block"><van-icon name="balance-o" />商家已缴纳{{product.balanceMoney}}元诚信金作为所售商品及服务的质量担保金</p>
<!--          <p style="display: inline-block">距离1.8km</p>-->
        </van-col>
        <van-col span="7" >
          <van-button round type="primary" size="mini" color="#d78b1a" style="padding: 0 0.8rem" @click="toShop">进店逛逛</van-button>
        </van-col>
      </van-row>
      <van-row style="font-size: 0.7rem;padding: 0.1rem 1rem">
        <van-col span="8" style="text-align: right"><van-icon size="16" name="passed" color="blue"/>质量保障</van-col>
        <van-col span="8"><van-icon size="16" name="passed" color="blue"/>极致服务</van-col>
        <van-col span="8" style="text-align: left"><van-icon size="16" name="passed" color="blue"/>售后无忧</van-col>
      </van-row>
    </div>
    <van-divider/>
    <div class="commodity-details-f">
      <van-row @click="guige">
        <van-col span="3">已选</van-col>
        <van-col span="16"  style="text-align: left" >选择 规格</van-col>
        <van-col span="3"><van-icon name="arrow" size="14" style="position: absolute;right: 1rem;"/></van-col>
      </van-row>
    </div>
    <van-divider/>
    <div class="commodity-details-i" align="left">
      <van-tabs type="card">
        <van-tab title="商品介绍" style="padding: 1rem 1rem">
          <P style="font-size: 1rem;margin-bottom: 0.1rem">产品信息</P>
          <div v-html="product.descript">{{}}</div>
          <van-image
            width="300"
            height="300"
            lazy-load
            v-for="url in infoImages" :key="url" :src="url"
          />
          <div class="demo-image__lazy">
            <el-image v-for="url in infoImages" :key="url" :src="url" lazy></el-image>
          </div>
        </van-tab>
<!--        <van-tab title="商品评价" style="padding: 1rem 1rem">-->
<!--          <P style="font-size: 1rem;margin-bottom: 0.1rem">产品评价</P>-->
<!--          <div v-html="product.descript">{{}}</div>-->
<!--&lt;!&ndash;          <v-html></v-html>&ndash;&gt;-->
<!--        </van-tab>-->
      </van-tabs>
    </div>
    <van-goods-action>
      <van-goods-action-icon icon="chat-o" text="客服" dot >
        <a :href="'tel:' + product.phoneNumber" rel="external nofollow" ><span style="color: black">客服</span>  </a>
      </van-goods-action-icon>
      <van-goods-action-icon @click="gouwuche" icon="cart-o" text="购物车"/>
      <van-goods-action-icon @click="toShop" icon="shop-o" text="店铺" />
      <van-goods-action-button type="warning" text="加入购物车" @click="goShoppingCart()" />
      <van-goods-action-button type="danger" text="立即购买" @click="purchase" />
    </van-goods-action>

    <van-sku
      align="left"
      v-model="show"
      :sku="sku"
      :goods="goods_info"
      :goods-id="goods_id"
      :hide-stock="sku.hide_stock"
      :quota-used="quota_used"
      reset-stepper-on-hide
      reset-selected-sku-on-hide
      :initial-sku="initialSku"
      disable-stepper-input
      :close-on-click-overlay="closeOnClickOverlay"
      :custom-sku-validator="customSkuValidator"
      @buy-clicked="onBuyClicked"
      :show-add-cart-btn="false"
      buy-text="确认"/>  <!-- disable-stepper-input  数字框左右的数字框可以按 里面的数字不能手动输入 -->

    <van-sku
      align="left"
      v-model="showCar"
      :sku="sku"
      :goods="goods_info"
      :goods-id="goods_id"
      :hide-stock="sku.hide_stock"
      :quota-used="quota_used"
      reset-stepper-on-hide
      reset-selected-sku-on-hide
      :initial-sku="initialSku"
      disable-stepper-input
      :close-on-click-overlay="closeOnClickOverlay"
      :custom-sku-validator="customSkuValidator"
      @buy-clicked="onAddCartClicked"
      :show-add-cart-btn="false"
      buy-text="确认"/>  <!-- disable-stepper-input  数字框左右的数字框可以按 里面的数字不能手动输入 -->

    <van-popup v-model="showCoupon" round position="bottom" closeable :style="{ height: '70%' }">
      <div class="container">
        <h1 style="color: red;font-size: 18px">优惠明细</h1>
        <div class="coupon-list">
          <div class="sawtooth-bor item" v-if="preferentialCard.length >0" v-for="preferential in preferentialCard">
            <div class="pt10 discount" style="padding-top: 10px;">
              <div class="fs12">{{preferential.preferentialName}}</div>
              <div class="fs12">满{{preferential.preferentialPriceMost}}减{{preferential.preferentialPrice}}</div>
              <div class="fs12">有效期{{preferential.modifiedTime}} - {{preferential.preferentialTime}}</div>
            </div>
            <div class="textc receive" @click="receivePreferential(preferential)">立即领取</div>
          </div>
          <van-divider />
          <h1 style="color: red;font-size: 18px;margin-bottom: 0.5rem"
          v-if="platformCoupon != null">平台优惠活动</h1>
          <div class="sawtooth-bor item">
            <div class="pt10 discount" style="padding-top: 10px;">
              <div class="fs12">{{platformCoupon.platformName}}</div>
              <div class="fs12">满{{platformCoupon.platformPriceMost}}减{{platformCoupon.platformPrice}}</div>
              <div class="fs12">有效期{{platformCoupon.platformTimeStart}} - {{platformCoupon.platformTimeEnd}}</div>
            </div>
            <div class="textc receive" @click="receivePlatformCoupon(platformCoupon)">立即领取</div>
          </div>
        </div>
      </div>
    </van-popup>
  </div>
</template>

<script>

  import { selectProductById,getInforPic,selectProductLableByProId,selectSupplierCoupon,selectPpiUrl,xiaoliang } from '@/api/commodity/shop_product.js'
  import { installCustomerCode,addPlatformCouponCustomerCode } from '@/api/customer/customer.js'
  import { addOrderShoppingCart } from '@/api/commodity/shopping_cart.js'
  import { Toast } from "vant";

  export default {
    name: "commodity_details",
    data(){
      return {
        xiaoshoushu:'',
        showCoupon:false,
        images: [
          // 'https://img.yzcdn.cn/vant/apple-1.jpg',
          // 'https://img.yzcdn.cn/vant/apple-2.jpg',
        ],
        current: 0,
        product :Object,
        supplierId: Number,
        show: false,
        showCar: false,
        sku: {
          // 所有sku规格类目与其值的从属关系，比如商品有颜色和尺码两大类规格，颜色下面又有红色和蓝色两个规格值。
          // 可以理解为一个商品可以有多个规格类目，一个规格类目下可以有多个规格值。
          tree: [
            {
              k: '规格',
              k_s: 's1',
              v: [],
            },
          ],

          // 所有 sku 的组合列表，如下是：白色1、白色2、天蓝色1、天蓝色2
          list: [],
          price: '',  //？？
          stock_num: null, // 商品总库存？？
          none_sku: false,  // 是否无规格商品 false正常显示那些可供选择的标准，此处是颜色和尺寸
          hide_stock: false,  // 是否隐藏剩余库存 false正常显示剩余多少件的那个库存
        },
        infoImages:[],
        initialSku:{
          // 键：skuKeyStr（sku 组合列表中当前类目对应的 key 值）
          // 值：skuValueId（规格值 id）
          s1: '1',
          // 初始选中数量
          selectedNum: 1,
        },
        goods_id: '',
        // quota: 6, //限购数量 库存旁边显示限购数
        quota_used: 0,  //已经购买过的数量picUrlAl 和下方的数字选择框显示不一样 与限购数量是相对应的 0数字选择框显示3   1 -- 2   2 -- 1  3 -- 0
        goods_info: {
          title: '',
          picture:''  //图片这个我有点混乱
        },
        showBase: true,    //sku的框的显示
        showCustom: false,
        showStepper: false,
        showSoldout: false,
        closeOnClickOverlay: true,  //点击空白处关闭购物框
        index: Array,
        productId: Number,
        // 平台优惠券
        platformCoupon :{},
        // 店铺优惠券
        preferentialCard :{},
        //添加购物车的参数
        orderShoppingCart:{
          productId:'',
          productLabelId:'',
          productNumber:'',
        },
        commodityId:'',
        buttons: [{
          title: '我的好友',
          extra: {
            scene: 'WXSceneSession'
          }
        },
          {
            title: '朋友圈',
            extra: {
              scene: 'WXSceneTimeline'
            }
          },
        ],
      };
    },
    created() {
      var id = parseInt(this.$route.query.commodityId);
      this.commodityId = id;
      this.productId = id;
      var productId = id;
      this.getProductById(id);
      this.getSelectPpiUrl(id);
      this.getInfoPics(id);
      // this.platformName(productId);
      this.findxiaoliang(id);
    },
    mounted() {
      if(window.plus) {
        this.updateSerivces();
      }
    },
    methods: {

      findxiaoliang(id){
        xiaoliang(id).then(res=>{
          this.xiaoshoushu = res.data.data
        })
      },

      /**
       * 获取微信分享通道
       */
      updateSerivces() {
        let _this = this;
        plus.share.getServices(function (s) {
          _this.shares = {};
          for (var i in s) {
            var t = s[i];
            _this.shares[t.id] = t;
          }
          _this.sweixin = _this.shares['weixin'];
          _this.sqq = _this.shares['qq'];
          _this.sinaweibo = _this.shares['sinaweibo'];
        }, function (e) {
          plus.nativeUI.alert('获取分享服务列表失败：' + e.message);
        });
      },
      //第三方分享
      share(a) {
        let _this = this;

        if(a == 'weixin'){
          let msg = {
            type: 'web', //分享的内容的类型
            title: '淘小建自建房平台美图太赞了,分享给你',
            content: this.product.productName,
            thumbs: [this.product.picUrlAl],
            href: 'http://51jhf.com/txj/#/commodity_details?commodityId='+this.commodityId,
            extra: {
              scene: "WXSceneSession"
            } // 'WXSceneSession'分享给好友，'WXSceneTimeline'分享到朋友圈
          }
          plus.nativeUI.actionSheet({
            title: '分享到微信',
            cancel: '取消',
            buttons: _this.buttons,
          }, function (e) {
            (e.index > 0) && _this.sharePage(_this.sweixin, msg, _this.buttons[e.index - 1]);
          })
        }
      },

      /**
       * 触发分享
       */
      sharePage(srv, msg, button) {
        let _this = this;
        // plus.nativeUI.alert('分享操作：');
        if (!srv) {
          plus.nativeUI.alert('无效的分享服务！');
          return;
        }
        button && (msg.extra = button.extra);
        // 发送分享
        if (srv.authenticated) {
          // plus.nativeUI.alert('---已授权---');
          _this.doShare(srv, msg);
        } else {
          // plus.nativeUI.alert('---未授权---');
          srv.authorize(function () {
            _this.doShare(srv, msg);
          }, function (e) {
            plus.nativeUI.alert('认证授权失败：' + JSON.stringify(e));
          });
        }
      },
      /**
       * 开始分享
       */
      doShare(srv, msg) {
        let _this = this;
        srv.send(msg, function () {
          plus.nativeUI.alert('分享到"' + srv.description + '"成功！');
        }, function (e) {
          plus.nativeUI.alert('分享到"' + srv.description + '"失败: ' + JSON.stringify(e));
        });
      },




      toBack(){
        this.$router.go(-1);//返回上一层
      },
      onChange(index) {
        this.current = index;
      },

      gouwuche(){
        this.$router.push({path:"/ShoppingCart"});
      },

      toShop(){
        this.$router.push({path:"/shop_home",query:{shopId:this.supplierId}});
      },
      getProductById(productId){
        selectProductById(productId).then((res) => {
          this.product = res.data.data;
          this.supplierId = res.data.data.supplierId;
          this.goods_info.title = res.data.data.productName;
          this.sku.price = res.data.data.price;
           this.goods_info.picture= res.data.data.picUrlAl
           this.getSupplierCoupon(res.data.data.supplierId);
        });
      },
      //获取产品详情图片
      getInfoPics(productId){
        console.log("********22222*****"+productId);
        getInforPic(productId).then((res) => {
          for (let i = 0; i < res.data.data.length; i++){
            this.infoImages.push(res.data.data[i].productDetailsUrl);
          }
        });
      },

      guige(){
        this.show = true;
        this.sku.tree = [
          {
            k: '规格',
            k_s: 's1',
            v: [],
          },
        ];
        selectProductLableByProId(this.productId).then((res) =>{
          for (let i = 0; i < res.data.data.length; i++){
            this.sku.tree[0].v.push({ "id": res.data.data[i].labelId,"name":res.data.data[i].labelName,"imgUrl":res.data.data[i].productPicInfo.picUrl});
            this.sku.list.push({ "id": null,"price":(res.data.data[i].labelPrice)*100,"discount":null,
              "s1":res.data.data[i].labelId,"stock_num":parseInt(res.data.data[i].labelQuantity),"goods_id":res.data.data[i].productId});
            this.goods_id = res.data.data[i].productId;
            this.sku.stock_num += parseInt(res.data.data[i].labelQuantity);
          }
          // console.log(this.sku.tree);
          // console.log(res.data);
        });
      },


      purchase(){
        // debugger
        this.show = true;
        this.sku.tree = [
          {
            k: '规格',
            k_s: 's1',
            v: [],
          },
        ];
        selectProductLableByProId(this.productId).then((res) =>{
          for (let i = 0; i < res.data.data.length; i++){
            this.sku.tree[0].v.push({ "id": res.data.data[i].labelId,"name":res.data.data[i].labelName,"imgUrl":res.data.data[i].productPicInfo.picUrl});
            this.sku.list.push({
              "id": null,
              "price":(res.data.data[i].labelPrice)*100,
              "discount":null,
              "s1":res.data.data[i].labelId,
              "stock_num":parseInt(res.data.data[i].labelQuantity),
              "goods_id":res.data.data[i].productId
            });
            this.goods_id = res.data.data[i].productId;
            this.sku.stock_num += parseInt(res.data.data[i].labelQuantity);
          }
          // console.log(this.sku.tree);
          // console.log(res.data);
        });
      },
      customSkuValidator(){

      },
      onBuyClicked(sku) {
        // console.log(JSON.stringify(sku.selectedNum));
        this.$router.push({
          path:"/OrderDetails",
          query:{
            skuId: sku.selectedSkuComb.s1,
            productId:this.product.productId,
            selectedNum:sku.selectedNum,
            supplierId:this.supplierId
          }});
        // this.$router.push({path:"/PaymentDetails",query:{skuId: sku.selectedSkuComb.s1,productId:this.product.productId,selectedNum:sku.selectedNum}});
      },
      onAddCartClicked(sku) {

        console.log(sku.selectedSkuComb.s1,"规格id",this.product.productId,"商品id",sku.selectedNum,"购买数量")
        this.orderShoppingCart.productId = this.product.productId;
        this.orderShoppingCart.productLabelId = sku.selectedSkuComb.s1;
        this.orderShoppingCart.productNumber = sku.selectedNum;
        if(this.orderShoppingCart.productLabelId != ''){
          addOrderShoppingCart(this.orderShoppingCart).then((res)=>{
            if(res.data==1){
              Toast({
                message: "添加购物车成功",
                position: "top"
              });
              this.show = false;
            }
          })
        }
        this.showCar = false;
      },
      // 查询店铺优惠券
      getSupplierCoupon(id){
        selectSupplierCoupon(id).then((res) =>{
          this.preferentialCard = res.data.preferentialCard;
          this.platformCoupon = res.data.platformCoupon;
          console.log(res.data)
        })
      },
      // 领取店铺优惠券
      receivePreferential(preferential){
        installCustomerCode(preferential).then((res) =>{
          if(res.data.code == 200){
            Toast({
              message: "领取成功",
              position: "top"
            });
          }else{
            Toast({
              message: "领取失败,请勿重复领取",
              position: "top"
            });
          }
        })
      },
      // 领取平台优惠券
      receivePlatformCoupon(platformCoupon){
        platformCoupon.supplierId = this.supplierId;
        addPlatformCouponCustomerCode(platformCoupon).then((res) =>{
          if(res.data.code == 200){
            Toast({
              message: "领取成功",
              position: "top"
            });
          }else{
            Toast({
              message: "领取失败,请勿重复领取",
              position: "top"
            });
          }
        })
      },
      //根据商品的id查询规格图片的轮播
      getSelectPpiUrl(productId){
        selectPpiUrl(productId).then((res)=>{
          this.images = res.data.data;
        })
      },
      //加入购物车
      goShoppingCart(){
        this.showCar = true;
        this.sku.tree = [
          {
            k: '规格',
            k_s: 's1',
            v: [],
          },
        ];
        selectProductLableByProId(this.productId).then((res) =>{
          for (let i = 0; i < res.data.data.length; i++){
            this.sku.tree[0].v.push({ "id": res.data.data[i].labelId,"name":res.data.data[i].labelName,"imgUrl":res.data.data[i].productPicInfo.picUrl});
            this.sku.list.push({ "id": null,"price":(res.data.data[i].labelPrice)*100,"discount":null,
              "s1":res.data.data[i].labelId,"stock_num":parseInt(res.data.data[i].labelQuantity),"goods_id":res.data.data[i].productId});
            this.goods_id = res.data.data[i].productId;
            this.sku.stock_num += parseInt(res.data.data[i].labelQuantity);
          }
        });
      },

    },
  }
</script>

<style scoped>
  /*.commodity-details{*/
  /*  color: black;*/
  /*  !*padding-bottom: 60px;*!*/
  /*}*/
  /*.demo-nav{*/
  /*  position: relative;*/
  /*  display: flex;*/
  /*  -webkit-box-align: center;*/
  /*  align-items: center;*/
  /*  -webkit-box-pack: center;*/
  /*  justify-content: center;*/
  /*  height: 56px;*/
  /*  background-color: #fff;*/
  /*  font-size: 1.1rem;*/
  /*}*/
  /*.demo-nav__back{*/
  /*  position: absolute;*/
  /*  top: 16px;*/
  /*  left: 16px;*/
  /*  width: 24px;*/
  /*  height: 24px;*/
  /*  cursor: pointer;*/
  /*}*/
  /*.demo-nav__right{*/
  /*  position: absolute;*/
  /*  top: 18px;*/
  /*  right: 16px;*/
  /*}*/
  .commodity-details-a{
    padding: 0.5rem 1rem;
  }
  .commodity-details-a p{
    font-size: 0.8rem;
  }
  .commodity-details-b{
    padding: 0 1rem;
  }
  .commodity-details-c{
    padding: 0.3rem 1rem;
  }
  .commodity-details-c p{
    font-size: 0.75rem;
    padding: 0.2rem 0;
  }
  .commodity-details-e{
    padding: 0.3rem 1rem;
    position: relative;
    font-size: 0.5rem;
  }
  .commodity-details-f{
    padding: 0.3rem 1rem;
    font-size: 1rem;
    position: relative
  }
  .commodity-details-i{
    padding: 0.3rem 1rem;
  }
  .commodity-details-i p{
    font-size: 0.6rem;
  }

  .container {
    position: absolute;
    width: 100%;
    height: 100%;
    margin: 0;
    padding-top: 18px;
  }

  .coupon-list {
    width: 370px;
    margin: 0 auto;
  }

  .coupon-list .item:first-child {
    margin-top: 20px;
  }

  .coupon-list .item {
    width: 370px;
    height: 90px;
    margin-bottom: 20px;
    display: flex;
    justify-content: space-between;
  }
  /* 第一个 */
  .sawtooth-bor {
    display: flex;
    color: #fff;
    padding-left: 0.5rem;
    box-sizing: border-box;
    /* 画出一个半径为8rpx的透明的圆，透明圆以外都是#ffb937颜色 */
    background: radial-gradient(transparent 0, transparent 8px, #F35C3B 8px);
    /* 截取上面生成的渐变图的一部分，相当于截取30rpx的正方形中有一个直径10px的透明圆点 */
    background-size: 30px 28px;
    /* 根据优惠券div大小进行微调 */
    background-position: 16px 0px;
    background-color: #fff;
    position: relative;
  }

  .sawtooth-bor:before {
    content: ' ';
    display: block;
    /* 用相同的颜色覆盖 */
    background-color: #F35C3B;
    /* 绝对定位，遮住中间所有的洞，只保留边角的锯齿 */
    position: absolute;
    top: 0;
    bottom: 0;
    /* 为锯齿保留的距离 */
    left: 20px;
    right: 20px;
    z-index: -1;
  }

  .discount {
    border-right: 2px dashed #f5f5f5;
    padding: 10px;
    flex: 1;
    box-sizing: border-box;
    background-color: #F35C3B;
  }

  .receive {
    display: flex;
    justify-content: center;
    align-items: center;
    width: 104px;
    height: 100%;
    padding: 20px;
    box-sizing: border-box;
    background-color: #ffb937;
  }

</style>
